﻿using CoffeeShop.BIZ;
using CoffeeShop.Common;
using CoffeeShop.Models.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CoffeeShop.Controllers
{
    public class ProductController : Controller
    {
        private ProductBiz _productBiz = new ProductBiz();
        private CategoryBiz _categoryBiz = new CategoryBiz();
        private UnitBiz _unitBiz = new UnitBiz();

        [Authorize(Roles = "Admin, Staff")]
        public ActionResult Index()
        {
            List<Product> listProduct = new List<Product>();
            listProduct = _productBiz.GetListProducts();
            return View(listProduct);
        }

        /// <summary>
        /// Create a Product
        /// </summary>
        [HttpPost]
        [Authorize(Roles = "Admin, Staff")]
        public string CreateProduct(FormCollection data)
        {
            string productName = data["categoryName"].Trim();
            string unitId = data["unitId"].Trim();
            string price = data["price"].Trim();
            string categoryId = data["categoryId"].Trim();
            HttpPostedFileBase fileImage = Request.Files["fileImage"];
            
            if (!_productBiz.IsValidProductModel(productName, unitId, price, categoryId))
            {
                return "CreateFail";
            }

            if (_productBiz.IsExistedProductCreate(productName, Convert.ToInt32(categoryId)))
            {
                return "ExistedProduct";
            }

            var fileImageName = string.Empty;
            if (fileImage != null)
            {
                fileImageName = DateTime.Now.ToString("ddMMyyyyhhmmss_") + fileImage.FileName;
                string imagePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath(CmnFunc.PRODUCT_IMAGE_PATH), Path.GetFileName(fileImageName));
                fileImage.SaveAs(imagePath);
            }

            Product product = new Product();
            product = _productBiz.ConvertToProductObject(productName, Convert.ToInt32(unitId), Convert.ToDouble(price), Convert.ToInt32(categoryId), fileImageName);
            if (_productBiz.CreateProduct(product))
            {
                return "CreateSuccessful";
            }
            return "CreateFail";
        }

        /// <summary>
        /// Update a Product
        /// </summary>
        [HttpPost]
        [Authorize(Roles = "Admin, Staff")]
        public string UpdateProduct()
        {
            // Get param value
            string productId = Request.Params["productId"].Trim();
            string productName = Request.Params["productName"].Trim();
            string unitId = Request.Params["unitId"].Trim();
            string price = Request.Params["price"].Trim();
            string categoryId = Request.Params["categoryId"].Trim();
            HttpPostedFileBase fileImage = Request.Files["fileImage"];

            // Validate model again
            if (!_productBiz.IsValidProductModel(productName, unitId, price, categoryId))
            {
                return "UpdateFail";
            }

            var productModel = _productBiz.GetProductById(Convert.ToInt32(productId));

            // Detele old file
            var fileImageName = string.Empty;
            if (fileImage != null)
            {
                // If have old image file -> Delete the old image file
                if (!string.IsNullOrEmpty(productModel.ImageURL))
                {
                    System.IO.File.Delete(HttpContext.Server.MapPath(CmnFunc.PRODUCT_IMAGE_PATH) + productModel.ImageURL);
                }                

                // Save new file
                fileImageName = DateTime.Now.ToString("ddMMyyyyhhmmss_") + fileImage.FileName;
                string imagePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath(CmnFunc.PRODUCT_IMAGE_PATH), Path.GetFileName(fileImageName));
                fileImage.SaveAs(imagePath);
            }

            if (_productBiz.IsExistedProductUpdate(Convert.ToInt32(productId), productName, Convert.ToInt32(categoryId)))
            {
                return "ExistedProduct";
            }

            if (_productBiz.UpdateProduct(productModel))
            {
                return "UpdateSuccessful";
            }

            return "UpdateFail";
        }

        /// <summary>
        /// Delete an area in Database
        /// </summary>
        [HttpPost]
        [Authorize(Roles = "Admin, Staff")]
        public string DeleteProduct(string productId)
        {
            if (string.IsNullOrEmpty(productId))
            {
                return "FailDeleteProduct";
            }
            if (_productBiz.DeleteProduct(Convert.ToInt32(productId)))
            {
                return "DeleteSuccessful";
            }

            return "FailDeleteProduct";
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Staff")]
        public PartialViewResult LoadAllProducts()
        {
            List<Product> listAllProducts = new List<Product>();
            listAllProducts = _productBiz.GetListProducts();
            return PartialView("_ProductList", listAllProducts);
        }

        public JsonResult GetProductById(string productId)
        {
            Product product = new Product();
            product = _productBiz.GetProductById(Convert.ToInt32(productId));
            product.ImageURL = Common.CmnFunc.PRODUCT_IMAGE_PATH_SHOW + product.ImageURL;
            return Json(new { ProductId = product.ID, ProductName = product.Name, UnitId = product.UnitId, UnitName = product.Unit.Name, Price = product.Price,
                              CategoryId = product.CategoryId, CategoryName = product.Category.Name, ImageURL = product.ImageURL, IsDeleted = product.IsDeleted }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Get list category to send value to object
        /// </summary>
        /// <returns></returns>
        public JsonResult GetListCategory()
        {
            List<Category> listCategory = new List<Category>();
            listCategory = _categoryBiz.GetListCategories();

            List<Object> listResult = new List<Object>();
            foreach (var category in listCategory)
            {
                var result = CmnFunc.ConvertDynamicObjectWithFullAttr(category);
                listResult.Add(result);
            }
            return Json(listResult, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Get list units to send value to object
        /// </summary>
        /// <returns></returns>
        public JsonResult GetListUnit()
        {
            List<Unit> listUnit = new List<Unit>();
            listUnit = _unitBiz.GetListUnits();

            List<Object> listResult = new List<Object>();
            foreach (var unit in listUnit)
            {
                var result = CmnFunc.ConvertDynamicObjectWithFullAttr(unit);
                listResult.Add(result);
            }
            return Json(listResult, JsonRequestBehavior.AllowGet);
        }
    }
}
